
package org.jetnuke.dao.generic;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import net.jforum.JForumExecutionContext;
import net.jforum.dao.generic.AutoKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.jetnuke.entities.EncyclopediaText;

public class GenericEncyclopediaTextDAO extends AutoKeys implements
		org.jetnuke.dao.EncyclopediaTextDAO {

	/* (non-Javadoc)
	 * @see org.jetnuke.model.EncyclopediaTextModel#retrieveByPK(int)
	 */
	public EncyclopediaText retrieveByPK(int id) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("EncyclopediaTextModel.selectByID"));
		p.setInt(1, id);
		
		ResultSet rs = p.executeQuery();
		EncyclopediaText  s = new EncyclopediaText ();
		
		if (rs.next()) {
			fillEncyTextFromResultSet(s, rs);
		}
		
		rs.close();
		p.close();

		return s;
	}

	/**
	 * @param s
	 * @param rs
	 */
	protected void fillEncyTextFromResultSet(EncyclopediaText s, ResultSet rs)throws Exception {
		s.setCOUNTER(rs.getInt("COUNTER"));
		s.setEID(rs.getInt("EID"));
		s.setTEXT(rs.getString("TEXT"));
		s.setTID(rs.getInt("TID"));
		s.setTITLE(rs.getString("TITLE"));
		
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.EncyclopediaTextModel#addNew(org.jetnuke.entities.EncyclopediaText)
	 */
	public int addNew(EncyclopediaText etext) throws Exception {
		PreparedStatement p = this.getStatementForAutoKeys("EncyclopediaTextModel.addNew");
		this.setAutoGeneratedKeysQuery(SystemGlobals.getSql("EncyclopediaTextModel.lastGeneratedEncyTextID"));
		initEncyText(etext, p);
		
		int id = this.executeAutoKeysQuery(p);
		p.close();		
		return id;
	}

	/**
	 * @param etext
	 * @param p
	 */
	private void initEncyText(EncyclopediaText etext, PreparedStatement p) throws Exception{
		p.setInt(1,etext.getCOUNTER());
		p.setInt(2,etext.getEID());
		p.setString(3,etext.getTEXT());
		p.setString(4,etext.getTITLE());
		
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.EncyclopediaTextModel#countByEid(int)
	 */
	public int countByEid(int eid) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("EncyclopediaTextModel.countByEid"));
		p.setInt(1,eid);
		ResultSet rs = p.executeQuery();
		rs.next();
		
		
		int r= rs.getInt(1);
		rs.close();
		p.close();
		return r;
	}

}
